import { defineComponent, nextTick, onMounted, ref } from "vue";
import { formDark, FormItemRule, NButton, NForm, NFormItem, NImage, NInput, useMessage, } from "naive-ui"
import Flexform from "../../components/flexform";
import useOftenAttr from "../../hooks/oftenattr";
import { useRouter } from "vue-router";
import { useUserInfo } from "../../store/moduls/userinfo";
import { storeToRefs } from "pinia";
const checknum = (rule: FormItemRule, value: string) => {
  const regx = /^\d+$/
  if (!value) {
    return true
  } else if (!regx.test(value)) {
    return Error("请输入数字")
  } else if (value.length > 10) {
    return Error("最多输入10位字符")
  } else {
    return true
  }
}
export default defineComponent({
  name: "Login",
  setup() {
    const useraction = useUserInfo()
    const { name, username, id } = storeToRefs(useraction)
    const router = useRouter()
    const { message, http } = useOftenAttr()
    // 回车按下的无效化
    const meiyongfunc = (event: KeyboardEvent, key: string = "") => {
      if (event.key === "Enter") {
        if (key === "huiche") {
          handleClick()
        } else {
          event.preventDefault()
        }
      }
    }
    // 背景图片
    const bgimg = ref<string>("")
    // 验证码图片
    const codeimag = ref('')
    const formValue = ref<any>({}) // 表单数据
    // 更新验证码图片
    const refushimg = () => {
      http.getcode().then((res: any) => {
        if (res.data.code === 0) {
          codeimag.value = res.data.data.imgurl
          formValue.value["codeid"] = res.data.data.codeid
        } else {
          message.error("获取验证码图片失败")
        }
      })
    }
    // 表单配置
    const formList = ref([
      {
        label: '账号',
        key: 'username',
        type: 'input',
        rules: [
          {
            required: true,
            message: '请输入账号',
            trigger: ['input', 'change', 'blur'],
          },
          {
            max: 200,
            min: 2,
            message: '请输入2-200为的字符',
            trigger: ['input', 'change', 'blur'],
          },
        ],
      },
      {
        label: '密码',
        key: 'password',
        type: 'input',
        password: 'password',
        rules: [
          {
            required: true,
            message: '请输入密码',
            trigger: ['input', 'change', 'blur'],
          },
          {
            max: 200,
            min: 2,
            message: '请输入2-200为的字符',
            trigger: ['input', 'change', 'blur'],
          },
        ],
      },
      {
        label: '验证码',
        key: 'code',
        slot: (item: any,shauxin:Function) => (<NFormItem label={item.label + "："} path={item.path || item.key} rule={item.rules || []}>
          <div class="w-full flex justify-between items-center overflow-hidden">
            <NInput v-model={[formValue.value[item.key], "value"]} onKeydown={(event) => meiyongfunc(event, "huiche")} type={item.passwordtype || "text"}
              placeholder={item.placeholder || "请输入"} clearable={item.clearable} disabled={item.disabled}
              size={item.size || "small"}  onUpdateValue={(val) => shauxin(item.key, val)} >
            </NInput>
            <NImage height={26} preview-disabled={true} src={codeimag.value} class="border border-gray-300" onClick={refushimg} />
          </div>
        </NFormItem>
        ),
        type: 'slot',
        rules: [
          {
            required: true,
            message: '请输入验证码',
            trigger: ['input', 'change', 'blur'],
          },
          {
            validator: checknum, trigger: ['input', 'change', 'blur'],
          },
        ],
      },
    ])
    const formref = ref<any>(null)
    // 点击登录
    const handleClick = () => {
      formref.value?.jiaoyan(() => {
          console.log(formValue.value,"formValue.value")
          http.login(formValue.value).then((res: any) => {
            if (res.data.code === 0) {
              useraction.denglu(res.data.data)
              message.success("登录成功")
              router.push({ name: "Main" })
            } else {
              message.error(res.data?.error || "登录失败")
            }
          })
      })
    }
    // 获取匿名用户信息
    const getanymouse = () => {
      http.anylogin({}).then((res: any) => {
        if (res.data.code === 0) {
          console.log("获取匿名成功", res);
          useraction.denglu(res.data.data)
        } else {
          message.error("获取token失败")
        }
      })
    }

    // 初始化函数
    const init = () => {
      console.log(id, !id, "什么情况啊");

      // 如果当前没有id，将获取匿名用户
      if (!id.value) {
        getanymouse()
      }
      // 获取新的验证码图片
      refushimg()
      console.log({...formValue.value},"init")
      nextTick(()=>{
        console.log({...formValue.value},"nextTick")
      })
    }
    // 初始化区域
    init()
    onMounted(()=>{
      nextTick(()=>{
        console.log({...formValue.value},"onMounted")
      })
    })
    return () => (
      <div class="w-full h-full flex flex-col justify-center items-center">
        <div class="w-400px h-400px flex flex-col justify-center items-center border border-gray-200 shadow-full p-5">
          <h1 class="w-full h-10 mb-3 text-center titletext">登录</h1>
          <Flexform ref={formref} formList={formList.value} v-model={[formValue.value, "value"]} class="w-full"></Flexform>
          <div class="w-full h-10 juzhong1 mt-5">
            <NButton type={"primary"} class="w-1/2" onClick={handleClick}>登录</NButton>
          </div>
        </div>
      </div>
    )
  },
})
